package com.aic.aicdetactor;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import com.aic.aicdetactor.analysis.CurveValuePair;
import com.aic.aicdetactor.analysis.FFTValuePair;
import com.aic.aicdetactor.analysis.ReceivedDataAnalysis;
import com.aic.aicdetactor.common.CommonDef;
import com.aic.aicdetactor.common.Constants;
import com.aic.aicdetactor.common.Setting;
import com.aic.aicdetactor.crash.AICApplication;
import com.aic.aicdetactor.util.LogUtil;
import com.aic.aicdetactor.util.SystemUtil;
import com.aic.aicdetactor.util.ToastUtil;
import com.aic.xj.app.sdk.HandlerConstants;
import com.aic.xj.app.util.StringUtil;
import com.aicmonitor.aicdetactorsimple.R;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class PageControl extends Fragment {

    public static Object _lock = new Object();
    public static ChartControl _timeChart = null;
    public static ChartControl _rateChart = null;
    private String TAG = "PageControl";
    public static ChartControl _temp_Curve_Chart = null;

    public static final String SELECT = "com.aicmonitor.aicdetactorsimple.control.selectBluetooth";
    private SelectReceiver mSelectReceiver;

    private EditText txt_default_A, txt_default_V, txt_default_D, txt_default_T, txt_default_E;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //注册广播
        mSelectReceiver = new SelectReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SELECT);
        //当网络发生变化的时候，系统广播会发出值为android.net.conn.CONNECTIVITY_CHANGE这样的一条广播
        getActivity().registerReceiver(mSelectReceiver, intentFilter);

        Bundle mBundle = getArguments();
        String title = mBundle.getString("arg");
        View contextView = null;
        if (title.equals(MainActivity.PAGE[0])) {
            contextView = inflater.inflate(R.layout.fragment_page_control, container, false);
            initControlPage(contextView);
        } else if (title.equals(MainActivity.PAGE[1])) {
            contextView = inflater.inflate(R.layout.fragment_page_value, container, false);
            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Fragment_Page_Value, contextView);//2016-11-07 liuhg添加
            initValuePage(contextView);
        } else if (title.equals(MainActivity.PAGE[2])) {
            contextView = inflater.inflate(R.layout.fragment_page_chart, container, false);
            initChartPage(contextView);
        } else if (title.equals(MainActivity.PAGE[3])) {
            contextView = inflater.inflate(R.layout.fragment_page_log, container, false);
            initLogPage(contextView);
        } else {
            contextView = inflater.inflate(R.layout.fragment_page_setting, container, false);
            initSettingPage(contextView);
        }
        return contextView;

    }

    public class SelectReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case SELECT:
//                    String result = _operator.open(address, 15000);
//                    if (result.equals("#OK")) {
//                        byte[] data = new byte[]{(byte) 0x7F, (byte) 0x17, (byte) 0xD4, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,};
//                        for (int i = 0; i < encodingnamebytes.length; i++) {
//                            data[i + 3] = encodingnamebytes[i];
//                        }
//                        byte[] response = _operator.ioControl(0xD4, data, 4000, 20);
//                        if (response != null && response[2] == (byte) 0xD4 && response[3] == (byte) 0x5A) {
//                            _handler.obtainMessage(Constants.HANDLER_IOCONTROL_SETNAME, 1, 0, newname).sendToTarget();
//                        } else {
//                            _handler.obtainMessage(Constants.HANDLER_IOCONTROL_SETNAME, 0, 0, newname).sendToTarget();
//                        }
//                    } else {
//                        _handler.obtainMessage(HandlerConstants.HANDLER_ERROR, 0, 0, "连接失败:" + result).sendToTarget();
//                    }

                    String sensorname = intent.getStringExtra("name");
                    if (sensorname != null) {
                        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Sensor_Name_Address, sensorname);//2016-11-07 liuhg添加
                        String key_sensor = "";
                        int shouldcheckpointindex = -1;
                        String calibrationrecord = "";
                        boolean flag = false;
                        String BLEAddress = sensorname.substring(sensorname.indexOf("[") + 1, sensorname.indexOf("]"));//如：A0:E6:F8:1F:69:99
                        String BLEMac = BLEAddress.replace(":", "");//如：A0E6F81F6999

                        Setting setting = new Setting();
                        String path_record = setting.get_CalibrationRecordFile();
                        calibrationrecord = SystemUtil.openFile(path_record);
                        if (!StringUtil.isNullOrWhiteSpace(calibrationrecord)) { //发现校准点记录文档，校准点记录文档内容不为空
                            String[] record = calibrationrecord.split("]");
                            String[] record_2 = new String[record.length];
                            for (int i = 0; i < record.length; i++) {
                                record_2[i] = record[i].substring(record[i].indexOf("[") + 1);
                                key_sensor = record_2[i].split(",")[0];//如：A0E6F81F6999
                                if (BLEMac.equals(key_sensor)) //记录文件里存在当前选中传感器的校准记录
                                {
                                    shouldcheckpointindex = Integer.parseInt(record_2[i].split(",")[1]);//如：12
                                    CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Index, shouldcheckpointindex);
                                    break;
                                }
                            }
                            if (shouldcheckpointindex == -1) { //记录文件里未当前选中传感器的校准记录
                                CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Index, 0);
                            }
                        } else { //没有发现校准点记录文档或校准点记录文档里没有内容
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Index, 0);
                        }
                        restoreTextViewValue((View) CacheControl.GetInstance().get(CacheControl.Key_Fragment_Page_Value), R.id.txt_calibration_bluetooth_info, CacheControl.Key_Sensor_Name_Address);
                        String curshouldcheckpointindex = String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration_Point_Index));
                        String proc = curshouldcheckpointindex + "/" + String.valueOf(ReceivedDataAnalysis.getCalibrationTotalPoints());//标定进度
                        if (Integer.parseInt(curshouldcheckpointindex) == ReceivedDataAnalysis.getCalibrationTotalPoints()) {
                            proc += CommonDef.TempuratureCalbFinish;
                        }
                        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Schedule, proc);
                        restoreTextViewValue((View) CacheControl.GetInstance().get(CacheControl.Key_Fragment_Page_Value), R.id.txt_calibration_schedule, CacheControl.Key_Tempurature_Calibration_Schedule);
                        int value = CommonDef.TempuratureCalibrationLowerLimit;
                        if (Integer.parseInt(curshouldcheckpointindex) == ReceivedDataAnalysis.getCalibrationTotalPoints()) {
                            value = ReceivedDataAnalysis.getShouldCalPointsValue(Integer.parseInt(curshouldcheckpointindex) - 1);//当前应校准点校准时，黑体箱应调整到的标准温度;
                        } else {
                            value = ReceivedDataAnalysis.getShouldCalPointsValue(Integer.parseInt(curshouldcheckpointindex));//当前应校准点校准时，黑体箱应调整到的标准温度;
                        }
                        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Value, value);
                        restoreTextViewValue((View) CacheControl.GetInstance().get(CacheControl.Key_Fragment_Page_Value), R.id.txt_calibration, CacheControl.Key_Tempurature_Calibration_Point_Value);

                        String path = setting.getData_Media_Director(CommonDef.FILE_TYPE_BaseSetting);
                        String filename = BLEMac + "-temp.txt";
                        if (SystemUtil.isFileExist(path, filename)) {
                            String curve = ReceivedDataAnalysis.getTemperatureCurve(filename);
                            if (ReceivedDataAnalysis.getCalibrationCurvePiontsValue(curve)) {
                                CurveValuePair valuePair = (CurveValuePair) CacheControl.GetInstance().get(CacheControl.Key_Calibration_Chart);
                                synchronized (PageControl._lock) {
                                    if (PageControl._temp_Curve_Chart != null) {
                                        PageControl._temp_Curve_Chart.changeData(valuePair.xValue, valuePair.yValue);
                                    }
                                }
                            }
                        }
                        initSensorPrams(txt_default_A, txt_default_V, txt_default_D, txt_default_T, sensorname);
                    }
                    break;
            }
        }
    }


    private void initControlPage(View view) {
        try {
            Spinner spn_datatype = (Spinner) view.findViewById(R.id.spn_datatype);
            spn_datatype.setSelection(1);


            Button btn_tips = view.findViewById(R.id.btn_tips);
            if (AICApplication.isTips) {
                btn_tips.setText("提示开");
            } else {
                btn_tips.setText("提示关");
            }

            final ListView lv = (ListView) view.findViewById(R.id.lv_sensor);
            txt_default_A = (EditText) view.findViewById(R.id.txt_default_A);
            txt_default_V = (EditText) view.findViewById(R.id.txt_default_V);
            txt_default_D = (EditText) view.findViewById(R.id.txt_default_D);
            txt_default_T = (EditText) view.findViewById(R.id.txt_default_T);

            txt_default_E = (EditText) view.findViewById(R.id.txt_default_E);
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(view.getContext());
            float emivissivity = sp.getFloat(CacheControl.Key_Value_Txt_Default_E, 0.98f);
            setEditTextValue(view, R.id.txt_default_E, emivissivity);
            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Value_Txt_Default_E, emivissivity);

            if (lv.getAdapter() == null) {
                @SuppressWarnings("unchecked")
                ArrayAdapter<String> adapter = (ArrayAdapter<String>) CacheControl.GetInstance().get(CacheControl.Key_AvailableSensor);
                lv.setAdapter(adapter);
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_SelectedSensor, position);
                        String sensorname = ((ArrayAdapter<String>) lv.getAdapter()).getItem(position);//如：SN160402254[A0:E6:F8:1F:69:99]
                        if (sensorname != null) {
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Sensor_Name_Address, sensorname);//2016-11-07 liuhg添加
                            String key_sensor = "";
                            int shouldcheckpointindex = -1;
                            String calibrationrecord = "";
                            boolean flag = false;
                            String BLEAddress = sensorname.substring(sensorname.indexOf("[") + 1, sensorname.indexOf("]"));//如：A0:E6:F8:1F:69:99
                            String BLEMac = BLEAddress.replace(":", "");//如：A0E6F81F6999

                            Setting setting = new Setting();
                            String path_record = setting.get_CalibrationRecordFile();
                            calibrationrecord = SystemUtil.openFile(path_record);
                            if (!StringUtil.isNullOrWhiteSpace(calibrationrecord)) //发现校准点记录文档，校准点记录文档内容不为空
                            {
                                String[] record = calibrationrecord.split("]");
                                String[] record_2 = new String[record.length];
                                for (int i = 0; i < record.length; i++) {
                                    record_2[i] = record[i].substring(record[i].indexOf("[") + 1);
                                    key_sensor = record_2[i].split(",")[0];//如：A0E6F81F6999
                                    if (BLEMac.equals(key_sensor)) //记录文件里存在当前选中传感器的校准记录
                                    {
                                        shouldcheckpointindex = Integer.parseInt(record_2[i].split(",")[1]);//如：12
                                        CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Index, shouldcheckpointindex);
                                        break;
                                    }
                                }
                                if (shouldcheckpointindex == -1) //记录文件里未当前选中传感器的校准记录
                                {
                                    CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Index, 0);
                                }
                            } else //没有发现校准点记录文档或校准点记录文档里没有内容
                            {
                                CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Index, 0);
                            }

                            restoreTextViewValue((View) CacheControl.GetInstance().get(CacheControl.Key_Fragment_Page_Value), R.id.txt_calibration_bluetooth_info, CacheControl.Key_Sensor_Name_Address);
                            String curshouldcheckpointindex = String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration_Point_Index));
                            String proc = curshouldcheckpointindex + "/" + String.valueOf(ReceivedDataAnalysis.getCalibrationTotalPoints());//标定进度
                            if (Integer.parseInt(curshouldcheckpointindex) == ReceivedDataAnalysis.getCalibrationTotalPoints()) {
                                proc += CommonDef.TempuratureCalbFinish;
                            }
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Schedule, proc);
                            restoreTextViewValue((View) CacheControl.GetInstance().get(CacheControl.Key_Fragment_Page_Value), R.id.txt_calibration_schedule, CacheControl.Key_Tempurature_Calibration_Schedule);
                            int value = CommonDef.TempuratureCalibrationLowerLimit;
                            if (Integer.parseInt(curshouldcheckpointindex) == ReceivedDataAnalysis.getCalibrationTotalPoints()) {
                                value = ReceivedDataAnalysis.getShouldCalPointsValue(Integer.parseInt(curshouldcheckpointindex) - 1);//当前应校准点校准时，黑体箱应调整到的标准温度;
                            } else {
                                value = ReceivedDataAnalysis.getShouldCalPointsValue(Integer.parseInt(curshouldcheckpointindex));//当前应校准点校准时，黑体箱应调整到的标准温度;
                            }
                            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Value, value);
                            restoreTextViewValue((View) CacheControl.GetInstance().get(CacheControl.Key_Fragment_Page_Value), R.id.txt_calibration, CacheControl.Key_Tempurature_Calibration_Point_Value);

                            String path = setting.getData_Media_Director(CommonDef.FILE_TYPE_BaseSetting);
                            String filename = BLEMac + "-temp.txt";
                            if (SystemUtil.isFileExist(path, filename)) {
                                String curve = ReceivedDataAnalysis.getTemperatureCurve(filename);
                                if (ReceivedDataAnalysis.getCalibrationCurvePiontsValue(curve)) {
                                    CurveValuePair valuePair = (CurveValuePair) CacheControl.GetInstance().get(CacheControl.Key_Calibration_Chart);
                                    synchronized (PageControl._lock) {
                                        if (PageControl._temp_Curve_Chart != null) {
                                            PageControl._temp_Curve_Chart.changeData(valuePair.xValue, valuePair.yValue);
                                        }
                                    }
                                }
                            }
                            initSensorPrams(txt_default_A, txt_default_V, txt_default_D, txt_default_T, sensorname);
                        }
                    }
                });
                lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
                Object index = CacheControl.GetInstance().get(CacheControl.Key_SelectedSensor);
                if (index != null) {
                    lv.setItemChecked((Integer) index, true);
                }
            }
            Object status = CacheControl.GetInstance().get(CacheControl.Key_Running_Status);
            if (status != null) {
                boolean s = (Boolean) status;
                if (!s) {
                    setControlStatus(view, false);
                }
            }
        } catch (Exception e) {
            LogUtil.GetInstance().append(e);
        }
    }

    private void setControlStatus(View view, boolean enable) {
        ListView lv = (ListView) view.findViewById(R.id.lv_sensor);
        if (lv != null) {
            lv.setEnabled(enable);
        }
        Spinner s = (Spinner) view.findViewById(R.id.spn_axistype);
        if (s != null) {
            s.setEnabled(enable);
        }
        s = (Spinner) view.findViewById(R.id.spn_datatype);
        if (s != null) {
            s.setEnabled(enable);
        }
        s = (Spinner) view.findViewById(R.id.spn_samplepoint);
        if (s != null) {
            s.setEnabled(enable);
        }
        s = (Spinner) view.findViewById(R.id.spn_samplerate);
        if (s != null) {
            s.setEnabled(enable);
        }

        EditText et = (EditText) view.findViewById(R.id.txt_default_A);
        if (et != null) {
            et.setEnabled(enable);
        }
        et = (EditText) view.findViewById(R.id.txt_default_D);
        if (et != null) {
            et.setEnabled(enable);
        }
        et = (EditText) view.findViewById(R.id.txt_default_T);
        if (et != null) {
            et.setEnabled(enable);
        }
        et = (EditText) view.findViewById(R.id.txt_default_V);
        if (et != null) {
            et.setEnabled(enable);
        }
    }

    private void initValuePage(View view) {
        try {
            LinearLayout layout_effective = (LinearLayout) view.findViewById(R.id.layout_effective_value);
            LinearLayout layout_high = (LinearLayout) view.findViewById(R.id.layout_high_value);
            LinearLayout layout_highhigh = (LinearLayout) view.findViewById(R.id.layout_highhigh_value);
            LinearLayout layout_rpm = (LinearLayout) view.findViewById(R.id.layout_rpm);
            LinearLayout layout_power = (LinearLayout) view.findViewById(R.id.layout_power);
            LinearLayout layout_calibration = (LinearLayout) view.findViewById(R.id.layout_calibration);
            LinearLayout layout_calibration_notice = (LinearLayout) view.findViewById(R.id.layout_calibration_notice);
            LinearLayout layout_calibration_btn = (LinearLayout) view.findViewById(R.id.layout_calibration_btn);
            LinearLayout layout_calibration_bluetooth_info = (LinearLayout) view.findViewById(R.id.layout_calibration_bluetooth_info);
            LinearLayout layout_chart_calibration_curve = (LinearLayout) view.findViewById(R.id.chart_calibration_curve);
            LinearLayout layout_temperature_v = (LinearLayout) view.findViewById(R.id.layout_temperature_v);
            TextView txt_calibration_unit = (TextView) view.findViewById(R.id.txt_calibration_unit);
            LinearLayout layout_slope = (LinearLayout) view.findViewById(R.id.layout_slope);
            LinearLayout layout_wavefactor = (LinearLayout) view.findViewById(R.id.layout_wavefactor);
            LinearLayout layout_peakfactor = (LinearLayout) view.findViewById(R.id.layout_peakfactor);
            LinearLayout layout_pulsefactor = (LinearLayout) view.findViewById(R.id.layout_pulsefactor);
            LinearLayout layout_clearancefactor = (LinearLayout) view.findViewById(R.id.layout_clearancefactor);
            LinearLayout layout_kurtosisfactor = (LinearLayout) view.findViewById(R.id.layout_kurtosisfactor);
            layout_calibration.setVisibility(View.GONE);
            layout_calibration_notice.setVisibility(View.GONE);
            layout_calibration_btn.setVisibility(View.GONE);
            layout_calibration_bluetooth_info.setVisibility(View.GONE);
            layout_chart_calibration_curve.setVisibility(View.GONE);
            layout_temperature_v.setVisibility(View.INVISIBLE);
            txt_calibration_unit.setVisibility(View.GONE);

            boolean flag = false;
            try {
                flag = (Boolean) CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration);
            } catch (Exception e) {
                // TODO: handle exception
                flag = false;
            }
            if (flag) {
                layout_effective.setVisibility(View.GONE);
                layout_high.setVisibility(View.GONE);
                layout_highhigh.setVisibility(View.GONE);
                layout_rpm.setVisibility(View.GONE);
                layout_power.setVisibility(View.GONE);
                layout_calibration.setVisibility(View.VISIBLE);
                layout_calibration_notice.setVisibility(View.VISIBLE);
                layout_calibration_btn.setVisibility(View.VISIBLE);
                layout_calibration_bluetooth_info.setVisibility(View.VISIBLE);
                layout_chart_calibration_curve.setVisibility(View.VISIBLE);
                layout_temperature_v.setVisibility(View.VISIBLE);
                txt_calibration_unit.setVisibility(View.VISIBLE);
                layout_slope.setVisibility(View.GONE);
                layout_wavefactor.setVisibility(View.GONE);
                layout_peakfactor.setVisibility(View.GONE);
                layout_pulsefactor.setVisibility(View.GONE);
                layout_clearancefactor.setVisibility(View.GONE);
                layout_kurtosisfactor.setVisibility(View.GONE);
            } else {
                layout_effective.setVisibility(View.VISIBLE);
                layout_high.setVisibility(View.VISIBLE);
                layout_highhigh.setVisibility(View.VISIBLE);
                layout_rpm.setVisibility(View.VISIBLE);
                layout_power.setVisibility(View.VISIBLE);
                layout_calibration.setVisibility(View.GONE);
                layout_calibration_notice.setVisibility(View.GONE);
                layout_calibration_btn.setVisibility(View.GONE);
                layout_calibration_bluetooth_info.setVisibility(View.GONE);
                layout_chart_calibration_curve.setVisibility(View.GONE);
                layout_temperature_v.setVisibility(View.INVISIBLE);
                txt_calibration_unit.setVisibility(View.GONE);
                layout_slope.setVisibility(View.VISIBLE);
                layout_wavefactor.setVisibility(View.VISIBLE);
                layout_peakfactor.setVisibility(View.VISIBLE);
                layout_pulsefactor.setVisibility(View.VISIBLE);
                layout_clearancefactor.setVisibility(View.VISIBLE);
                layout_kurtosisfactor.setVisibility(View.VISIBLE);
            }

            synchronized (PageControl._lock) {
                _temp_Curve_Chart = new ChartControl(view.getContext());

                LinearLayout layout = (LinearLayout) view.findViewById(R.id.chart_calibration_curve);
                if (layout != null) {
                    layout.removeAllViews();
                    layout.addView(_temp_Curve_Chart.get_chart(), new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                }

                Object values = CacheControl.GetInstance().get(CacheControl.Key_Calibration_Chart);
                if (values != null && _temp_Curve_Chart != null) {
                    CurveValuePair p = (CurveValuePair) values;
                    _temp_Curve_Chart.changeData(p.xValue, p.yValue);
                }
            }

            restoreTextViewValue(view, R.id.txt_calibration_ranage, CacheControl.Key_Tempurature_Calibration_Range);
            restoreTextViewValue(view, R.id.txt_calibration_step, CacheControl.Key_Tempurature_Calibration_Step);
            restoreTextViewValue(view, R.id.txt_calibration_schedule, CacheControl.Key_Tempurature_Calibration_Schedule);
            restoreTextViewValue(view, R.id.txt_calibration_bluetooth_info, CacheControl.Key_Sensor_Name_Address);

            int pointindex = 0;
            try {
                pointindex = Integer.parseInt(String.valueOf(CacheControl.GetInstance().get(CacheControl.Key_Tempurature_Calibration_Point_Index)));
            } catch (Exception e) {
                // TODO: handle exception
                CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Index, pointindex);
                LogUtil.GetInstance().append(e);
            }


            int pointvalue = ReceivedDataAnalysis.getShouldCalPointsValue(pointindex);
            CacheControl.GetInstance().addOrUpdate(CacheControl.Key_Tempurature_Calibration_Point_Value, pointvalue);
            restoreTextViewValue(view, R.id.txt_calibration, CacheControl.Key_Tempurature_Calibration_Point_Value);
            restoreTextViewValue(view, R.id.txt_temperature_voltage, CacheControl.Key_Tempurature_Voltage);
            restoreTextViewValue(view, R.id.txt_temperature, CacheControl.Key_Value_Temperature);
            restoreTextViewValue(view, R.id.txt_effective_value, CacheControl.Key_Value_Effective);
            restoreTextViewValue(view, R.id.txt_high_value, CacheControl.Key_Value_High);
            restoreTextViewValue(view, R.id.txt_highhigh_value, CacheControl.Key_Value_HighHigh);
            restoreTextViewValue(view, R.id.txt_power, CacheControl.Key_Value_Power);
            restoreTextViewValue(view, R.id.txt_rpm, CacheControl.Key_Value_RPM);

            restoreTextViewValue(view, R.id.txt_slope, CacheControl.Key_Value_Slope);
            restoreTextViewValue(view, R.id.txt_kurtosis, CacheControl.Key_Value_Kurtosis);
            restoreTextViewValue(view, R.id.txt_wavefactor, CacheControl.Key_Value_WaveFactor);
            restoreTextViewValue(view, R.id.txt_peakfactor, CacheControl.Key_Value_PeakFactor);
            restoreTextViewValue(view, R.id.txt_pulsefactor, CacheControl.Key_Value_PulseFactor);
            restoreTextViewValue(view, R.id.txt_clearancefactor, CacheControl.Key_Value_ClearanceFactor);
            restoreTextViewValue(view, R.id.txt_kurtosisfactor, CacheControl.Key_Value_KurtosisFactor);

            restoreTextViewValue(view, R.id.txt_effective_value_unit, CacheControl.Key_Value_Unit);
            restoreTextViewValue(view, R.id.txt_high_value_unit, CacheControl.Key_Value_Unit);
            restoreTextViewValue(view, R.id.txt_highhigh_value_unit, CacheControl.Key_Value_Unit);
        } catch (Exception e) {
            LogUtil.GetInstance().append(e);
        }
    }

    private void restoreTextViewValue(View view, int id, String key) {
        TextView tv = (TextView) view.findViewById(id);
        if (tv != null) {
            Object value = CacheControl.GetInstance().get(key);
            if (value != null) {
                tv.setText(String.valueOf(value));
            }
        }
    }

    private void setEditTextValue(View view, int id, Object obj) {
        EditText et = (EditText) view.findViewById(id);
        if (et != null) {
            et.setText(String.valueOf(obj));
        }
    }

    private void setEditTextValue(View view, int id, Object obj, int color) {
        EditText et = (EditText) view.findViewById(id);
        if (et != null) {
            et.setText(String.valueOf(obj));
            et.setTextColor(color);
        }
    }

    private void addTextChangedListener(final View view, int id, final String storageName) {
        EditText et = (EditText) view.findViewById(id);
        if (et != null) {
            et.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    try {
                        float f = Float.parseFloat(s.toString());
                        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(view.getContext());
                        Editor e = sp.edit();
                        e.putFloat(storageName, f);
                        e.commit();
                    } catch (Exception ex) {
                        if (AICApplication.isTips) {
                            ToastUtil.showToast(view.getContext(), "请填写一个正确的浮点数");
                        }
                    }
                }
            });
        }
    }

    private void initChartPage(View view) {
        try {
            synchronized (PageControl._lock) {
                _timeChart = new ChartControl(view.getContext());
                _rateChart = new ChartControl(view.getContext());

                LinearLayout layout = (LinearLayout) view.findViewById(R.id.chart_time);
                if (layout != null) {
                    layout.removeAllViews();
                    layout.addView(_timeChart.get_chart(), new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                }

                layout = (LinearLayout) view.findViewById(R.id.chart_rate);
                if (layout != null) {
                    layout.removeAllViews();
                    layout.addView(_rateChart.get_chart(), new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                }

                Object values = CacheControl.GetInstance().get(CacheControl.Key_Chart_Wave);
                Object fft = CacheControl.GetInstance().get(CacheControl.Key_Chart_FFT);

                if (values != null && _timeChart != null) {
                    _timeChart.changeData((float[]) values);
                }
                if (fft != null && _rateChart != null) {
                    FFTValuePair p = (FFTValuePair) fft;
                    _rateChart.changeData(p.FXs, p.FYs);
                }
            }

            restoreTextViewValue(view, R.id.txt_effective_value2, CacheControl.Key_Value_Effective);
            restoreTextViewValue(view, R.id.txt_high_value2, CacheControl.Key_Value_High);
            restoreTextViewValue(view, R.id.txt_highhigh_value2, CacheControl.Key_Value_HighHigh);

            restoreTextViewValue(view, R.id.txt_amplitude1, CacheControl.Key_Value_Amplitude1);
            restoreTextViewValue(view, R.id.txt_amplitude2, CacheControl.Key_Value_Amplitude2);
            restoreTextViewValue(view, R.id.txt_amplitude3, CacheControl.Key_Value_Amplitude3);

            restoreTextViewValue(view, R.id.txt_rate1, CacheControl.Key_Value_Rate1);
            restoreTextViewValue(view, R.id.txt_rate2, CacheControl.Key_Value_Rate2);
            restoreTextViewValue(view, R.id.txt_rate3, CacheControl.Key_Value_Rate3);

            TextView tv = (TextView) view.findViewById(R.id.txt_time_unit);
            if (tv != null) {
                Object value = CacheControl.GetInstance().get(CacheControl.Key_Value_Unit);
                if (value != null) {
                    tv.setText("Y " + String.valueOf(value));
                } else {
                    tv.setText("Y");
                }
            }
        } catch (Exception e) {
            LogUtil.GetInstance().append(e);
        }
    }

    private void initLogPage(View view) {
        try {
            ListView lv = (ListView) view.findViewById(R.id.lv_log);
            if (lv.getAdapter() == null) {
                lv.setAdapter((CustomListAdapter) CacheControl.GetInstance().get(CacheControl.Key_Log));
            }
        } catch (Exception e) {
            LogUtil.GetInstance().append(e);
            // btn_exit_Event(null);
        }
    }

    private void initSettingPage(View view) {
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    /**
     * 将传感器参数校正文件的数值显示在APP界面上
     *
     * @author liuhg
     */
    private void initSensorPrams(EditText txt_A, EditText txt_V, EditText txt_D, EditText txt_T, String sensorname) {// 2016-04-13 liuhg添加
        String BLEAddress = sensorname.substring(sensorname.indexOf("[") + 1, sensorname.indexOf("]"));
        if (StringUtil.isNullOrWhiteSpace(BLEAddress)) {
            getDefaultPramsFromRaw(txt_A, txt_V, txt_D, txt_T, "(默认参数校正文件)");
            return;
        }
        String curBluetoothAdressName = "当前设备:" + sensorname;
        String bluetoothAddress = BLEAddress.replace(":", "");
        String TempPramsName = null;
        String NormalPramsName = null;
        TempPramsName = bluetoothAddress + "-temp.txt";
        NormalPramsName = bluetoothAddress + "-vibrate.txt";
        getSelectedSensorPrams(txt_A, txt_V, txt_D, txt_T, TempPramsName, NormalPramsName, curBluetoothAdressName);
    }

    private void getSelectedSensorPrams(EditText txt_A, EditText txt_V, EditText txt_D, EditText txt_T, String TempPramsName, String NormalPramsName, String curBluetooth) {
        Setting setting = new Setting();
        String path = setting.getData_Media_Director(CommonDef.FILE_TYPE_BaseSetting);
        File fNormalPrams = new File(path + NormalPramsName);
        byte[] bufferNormalPrams = null;
        if (fNormalPrams.exists()) {
            try {
                FileInputStream finNormalPrams = new FileInputStream(path + NormalPramsName);
                if (finNormalPrams != null) {
                    bufferNormalPrams = new byte[finNormalPrams.available()];
                    finNormalPrams.read(bufferNormalPrams);
                    finNormalPrams.close();
                }
            } catch (Exception e) {
                Log.e(TAG, "读取本地校准文件出现异常:" + e.getMessage());
                LogUtil.GetInstance().append("读取本地校准文件出现异常:" + e.getMessage());
            }

            int FileLengthNormal = bufferNormalPrams.length;
            if (FileLengthNormal > 0) {
                String strMormalPrams = new String(bufferNormalPrams);
                String[] mormalPrams = strMormalPrams.split("\\*");
                if (mormalPrams.length < 4) {
                    if (AICApplication.isTips) {
                        ToastUtil.showToast(AICApplication.getApplication(), NormalPramsName + "文件：参数不全，将调用默认参数");
                    }
                    Log.e(TAG, NormalPramsName + "文件：参数不全，将调用默认参数");
                    getDefaultPramsFromRaw(txt_A, txt_V, txt_D, txt_T, curBluetooth + "\n" + NormalPramsName + "(尚未保存)");
                } else {
                    String[] shuju = new String[mormalPrams.length];
                    for (int i = 0; i < mormalPrams.length; i++) {
                        int start = mormalPrams[i].indexOf(":");
                        int end = mormalPrams[i].length();
                        shuju[i] = mormalPrams[i].substring(start + 1, end);
                    }
                    try {//这里有可能会空指针
                        if (txt_A == null || txt_V == null || txt_D == null || txt_T == null)
                            return;
                        txt_A.setText(shuju[1].toString());
                        txt_A.setTextColor(Color.BLACK);
                        txt_V.setText(shuju[2].toString());
                        txt_V.setTextColor(Color.BLACK);
                        txt_D.setText(shuju[3].toString());
                        txt_D.setTextColor(Color.BLACK);
                        txt_T.setText(shuju[0].toString());
                        txt_T.setTextColor(Color.BLACK);
                    } catch (Exception e) {
                        Log.e(TAG, NormalPramsName + "文件：校准数据格式有误，将调用默认参数");
                        ToastUtil.showToast(AICApplication.getApplication(), "文件：校准数据格式有误，将调用默认参数");
                        getDefaultPramsFromRaw(txt_A, txt_V, txt_D, txt_T, curBluetooth + "\n" + NormalPramsName + "(尚未保存)");
                    }
                }
            }
        } else {
            getDefaultPramsFromRaw(txt_A, txt_V, txt_D, txt_T, curBluetooth + "\n" + NormalPramsName + "(尚未保存)");
        }
    }

    /**
     * 获取APP默认振动温度参数配置文档中的参数
     *
     * @author liuhg
     */
    private void getDefaultPramsFromRaw(EditText txt_A, EditText txt_V, EditText txt_D, EditText txt_T, String content){// 2016-04-13 liuhg添加

        InputStream inputStreamNormalPrams = null;
        inputStreamNormalPrams = AICApplication.getApplication().getResources().openRawResource(R.raw.vibrate);
        byte[] bufferNormalPrams = null;
        try {
            bufferNormalPrams = new byte[inputStreamNormalPrams.available()];
        } catch (IOException e) {
            Log.e(TAG, "getDefaultPramsFromRaw执行bufferNormalPrams = new byte[inputStreamNormalPrams.available()]时出现异常" + e.getMessage());
            LogUtil.GetInstance().append("getDefaultPramsFromRaw执行bufferNormalPrams = new byte[inputStreamNormalPrams.available()]时出现异常" + e.getMessage());
        }
        try {
            inputStreamNormalPrams.read(bufferNormalPrams);
        } catch (IOException e) {
            Log.e(TAG, "getDefaultPramsFromRaw执行inputStreamNormalPrams.read(bufferNormalPrams)时出现异常" + e.getMessage());
            LogUtil.GetInstance().append("getDefaultPramsFromRaw执行inputStreamNormalPrams.read(bufferNormalPrams)时出现异常" + e.getMessage());
        }
        int FileLengthNormal = bufferNormalPrams.length;
        if (FileLengthNormal > 0) {
            String strMormalPrams = new String(bufferNormalPrams);
            String[] mormalPrams = strMormalPrams.split("\\*");
            String[] shuju = new String[mormalPrams.length];
            for (int i = 0; i < mormalPrams.length; i++) {
                int start = mormalPrams[i].indexOf(":");
                int end = mormalPrams[i].length();
                shuju[i] = mormalPrams[i].substring(start + 1, end);
            }
            try {
                txt_A.setText(shuju[1].toString());
                txt_A.setTextColor(Color.RED);
                txt_V.setText(shuju[2].toString());
                txt_V.setTextColor(Color.RED);
                txt_D.setText(shuju[3].toString());
                txt_D.setTextColor(Color.RED);
                txt_T.setText(shuju[0].toString());
                txt_T.setTextColor(Color.RED);

            } catch (Exception e) {
                LogUtil.GetInstance().append("getDefaultPramsFromRaw默认文件res/raw/vibrate校准数据格式有误" + e.getMessage());
            }
        }
    }
}